//
//  GQHLoginController.m
//  Xanthium
//
//  Created by GuanQinghao on 11/02/2018.
//  Copyright © 2018 GuanQinghao. All rights reserved.
//

#pragma mark Macro
#import "GQHHeader.h"

#pragma mark Model
#import "GQHUserModel.h"

#pragma mark Object

#pragma mark View
#import "GQHLoginView.h"
#import "GQHRegisterView.h"

#pragma mark Controller
#import "GQHLoginController.h"

#import "GQHRoleController.h"
#import "GQHPhoneController.h"
#import "GQHTabBarController.h"
#import "GQHPasswordSettingController.h"

#import "GQHAgreementController.h"
#import "GQHMobileController.h"

#import "JPUSHService.h"

#pragma mark CocoaPods

#pragma mark ----------Header End----------

@interface GQHLoginController () <GQHRegisterViewDelegate,GQHLoginViewDelegate> {
    
#pragma mark Data
    /// 用户模型
    GQHUserModel *userModel;
#pragma mark View
    /// 注册/登录按钮标记
    UIView *userLoginMarkView;
    UIView *userRegisterMarkView;
    /// 登录注册切换容器视图
    UIView *containerView;
}

@end


@implementation GQHLoginController

#pragma mark --Lifecycle
- (void)viewDidLoad {
    [super viewDidLoad];
    DLog();
    
    // 快速添加视图背景图
    self.view.layer.contents = (id)[UIImage imageNamed:@"login_background"].CGImage;
    
    [self loadUserInterface];
    [self displayLoginView:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    DLog();
    
    self.qh_leftButton.hidden = YES;
    self.qh_navigationBar.hidden = YES;
    self.qh_rightButton.hidden = YES;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    DLog();
    
}

#pragma mark --Delegate
#pragma mark ---登录
/// 验证手机号密码
- (void)qh_loginWithMobile:(NSString *)mobile password:(NSString *)password {
    
    [GQHUserModel qh_loginWithMobile:mobile password:password success:^(BOOL status, NSNumber *code, NSString *message, GQHUserModel *user) {
        
        if (status) {
            
            [[NSUserDefaults standardUserDefaults] setValue:user.qh_userTypeCode forKey:USER_TYPE];
            [[NSUserDefaults standardUserDefaults] setValue:user.auditState forKey:USER_STATUS];
            [[NSUserDefaults standardUserDefaults] setValue:password forKey:PASS_WORD];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            [self setJPushAlias];
            
            if ([user.qh_userTypeCode isEqualToString:@"0"]) {
                
                [[NSUserDefaults standardUserDefaults] setValue:@"03" forKey:USER_STATUS];
                
                GQHRoleController *roleController = [[GQHRoleController alloc] init];
                [self.navigationController pushViewController:roleController animated:YES];
            } else {
                
                GQHTabBarController *tabBarController = [[GQHTabBarController alloc] init];
                [[UIApplication sharedApplication] keyWindow].rootViewController = tabBarController;
            }
        } else {
            
            [self showToastWithText:message];
        }
    } failure:^(NSError *error) {
        
        NSString *errorString = [NSString stringWithFormat:@"网络出错:%@,code:%ld", error.domain, (long)error.code];
        [self showToastWithText:errorString];
    }];
}

- (void)setJPushAlias
{
    [JPUSHService setAlias:USER_GET_ID completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
        NSLog(@"------------rescode: %ld, \nseq: %ld, \nalias: %@\n", (long)iResCode, (long)seq, iAlias);
    } seq:1];
}

/// 忘记密码,跳转验证手机号页面
- (void)qh_forgetPassword {
    
    GQHPhoneController *phoneController = [[GQHPhoneController alloc] init];
    phoneController.qh_isRegistered = NO;
    [self.navigationController pushViewController:phoneController animated:YES];
}

#pragma mark ---注册
/// 请求验证码
- (void)qh_requestCodeWithMobile:(NSString *)mobile {
    
    [GQHUserModel qh_requestCodeWithMobile:mobile success:^(BOOL status, NSNumber *code, NSString *message, GQHUserModel *user) {
        
        if (0 == [code intValue]) {
            
            userModel = user;
        }
    } failure:^(NSError *error) {
        
        NSString *errorString = [NSString stringWithFormat:@"网络出错:%@,code:%ld", error.domain, (long)error.code];
        [self showToastWithText:errorString];
    }];
}

/// 验证手机号和验证码是否正确
- (void)qh_registerWithMobile:(NSString *)mobile code:(NSString *)codeString {
    
    if ([mobile isEqualToString:userModel.qh_mobile] && [codeString isEqualToString:userModel.qh_mobileCode]) {
        
        GQHPasswordSettingController *passwordSettingController = [[GQHPasswordSettingController alloc] init];
        passwordSettingController.qh_mobile = mobile;
        passwordSettingController.qh_isRegistered = YES;
        [self.navigationController pushViewController:passwordSettingController animated:YES];
    } else {
        
        [self qh_alertWithTitle:nil message:@"您输入的手机号验证码不匹配,请重新输入！" actionTitle:nil
                        handler:nil completion:nil];
    }
}

/// 查看平台注册协议内容
- (void)qh_checkAgreement {
    
    GQHAgreementController *agreementController = [[GQHAgreementController alloc] init];
    agreementController.qh_agreementType = GQHAgreementTypeRegistration;
    [self presentViewController:agreementController animated:YES completion:nil];
}

/// QQ快速登录
- (void)qh_loginWithQQ {
    
    
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:UMSocialPlatformType_QQ currentViewController:self completion:^(id result, NSError *error)
     {
         if (error)
         {
             
         }
         else
         {
             UMSocialUserInfoResponse *resp = result;
             // 授权信息
             NSLog(@"QQ uid: %@", resp.uid);
             NSLog(@"QQ openid: %@", resp.openid);
             NSLog(@"QQ accessToken: %@", resp.accessToken);
             NSLog(@"QQ expiration: %@", resp.expiration);
             // 用户信息
             NSLog(@"QQ name: %@", resp.name);
             NSLog(@"QQ iconurl: %@", resp.iconurl);
             NSLog(@"QQ gender: %@", resp.gender);
             // 第三方平台SDK源数据
             NSLog(@"QQ originalResponse: %@", resp.originalResponse);
             
             NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
             [parameters setObject:resp.openid forKey:@"openId"];
             [parameters setObject:resp.name forKey:@"name"];
             [parameters setObject:resp.iconurl forKey:@"hearImg"];
             [parameters setObject:@"02" forKey:@"sourceType"];
             
             NSString *URLString = [[NSString qh_APIURLString] stringByAppendingString:@"/loginRegist/1/chekThirdLogin"];
             
             [GQHNetHelper qh_requestGET:URLString parameters:parameters success:^(NSNumber *code, NSString *message, NSDictionary *data) {
                 DLog(@"%@--%@--%@",code,message,data);
                 
                 if (0 == [code intValue]) {
                     
                     NSString *result = [data objectForKey:@"result"];
                     if ([result isEqualToString:@"1"]) {
                         
                         /// 绑定手机号
                         GQHMobileController *mobileController = [[GQHMobileController alloc] init];
                         mobileController.qh_identifierType = @"binding";
                         mobileController.qh_mobile = USER_GET_MOBILE;
                         mobileController.qh_parameters = parameters;
                         mobileController.qh_done = YES;
                         mobileController.hidesBottomBarWhenPushed = YES;
                         [self.navigationController pushViewController:mobileController animated:YES];
                         
                     } else {
                         
                         GQHUserModel *userModel = [GQHUserModel yy_modelWithDictionary:data];
                         
                         [[NSUserDefaults standardUserDefaults] setObject:userModel.qh_userID forKey:USER_ID];
                         [[NSUserDefaults standardUserDefaults] setValue:userModel.qh_avatar forKey:USER_AVATAR];
                         [[NSUserDefaults standardUserDefaults] setObject:userModel.qh_userNickname forKey:USER_NAME];
                         [[NSUserDefaults standardUserDefaults] setObject:userModel.qh_mobile forKey:USER_MOBILE];
                         [[NSUserDefaults standardUserDefaults] setObject:userModel.qh_userTypeCode forKey:USER_TYPE];
                         [[NSUserDefaults standardUserDefaults] setObject:userModel.auditState forKey:USER_STATUS];
                         
                         NSNumber *score = [NSNumber numberWithFloat:userModel.qh_score];
                         [[NSUserDefaults standardUserDefaults] setValue:score forKey:USER_SCORE];
                         
                         [[NSUserDefaults standardUserDefaults] synchronize];
                         
                         if ([userModel.qh_userTypeCode isEqualToString:@"0"]) {
                             
                             [[NSUserDefaults standardUserDefaults] setValue:@"03" forKey:USER_STATUS];
                             
                             GQHRoleController *roleController = [[GQHRoleController alloc] init];
                             [self.navigationController pushViewController:roleController animated:YES];
                         } else {
                             
                             GQHTabBarController *tabBarController = [[GQHTabBarController alloc] init];
                             [[UIApplication sharedApplication] keyWindow].rootViewController = tabBarController;
                         }
                     }
                 } else {
                     
                     [self showToastWithText:message];
                 }
             } failure:^(NSError *error) {
                 
                 NSString *errorString = [NSString stringWithFormat:@"网络出错:%@,code:%ld", error.domain, (long)error.code];
                 [self showToastWithText:errorString];
             }];
             
             
//             [[NSUserDefaults standardUserDefaults] setObject:userModel.qh_userID forKey:USER_ID];
//             [[NSUserDefaults standardUserDefaults] setValue:userModel.qh_avatar forKey:USER_AVATAR];
//             [[NSUserDefaults standardUserDefaults] setObject:userModel.qh_userNickname forKey:USER_NAME];
//             [[NSUserDefaults standardUserDefaults] setObject:userModel.qh_mobile forKey:USER_MOBILE];
//             [[NSUserDefaults standardUserDefaults] setObject:userModel.qh_userTypeCode forKey:USER_TYPE];
//             [[NSUserDefaults standardUserDefaults] setObject:userModel.auditState forKey:USER_STATUS];
             
         }
     }];
}
/// wechat快速登录
- (void)qh_loginWithWechat {
    
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:UMSocialPlatformType_WechatSession currentViewController:self completion:^(id result, NSError *error)
     {
         if (error)
         {
             
         }
         else
         {
             UMSocialUserInfoResponse *resp = result;
             // 授权信息
             NSLog(@"Wechat uid: %@", resp.uid);
             NSLog(@"Wechat openid: %@", resp.openid);
             NSLog(@"Wechat accessToken: %@", resp.accessToken);
             NSLog(@"Wechat refreshToken: %@", resp.refreshToken);
             NSLog(@"Wechat expiration: %@", resp.expiration);
             // 用户信息
             NSLog(@"Wechat name: %@", resp.name);
             NSLog(@"Wechat iconurl: %@", resp.iconurl);
             NSLog(@"Wechat gender: %@", resp.gender);
             // 第三方平台SDK源数据
             NSLog(@"Wechat originalResponse: %@", resp.originalResponse);
             
             
             NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
             [parameters setObject:resp.openid forKey:@"openId"];
             [parameters setObject:resp.name forKey:@"name"];
             [parameters setObject:resp.iconurl forKey:@"hearImg"];
             [parameters setObject:@"01" forKey:@"sourceType"];
             
             NSString *URLString = [[NSString qh_APIURLString] stringByAppendingString:@"/loginRegist/1/chekThirdLogin"];
             
             [GQHNetHelper qh_requestGET:URLString parameters:parameters success:^(NSNumber *code, NSString *message, NSDictionary *data) {
                 DLog(@"%@--%@--%@",code,message,data);
                 
                 if (0 == [code intValue]) {
                     
                     NSString *result = [data objectForKey:@"result"];
                     if ([result isEqualToString:@"1"]) {
                         
                         /// 绑定手机号
                         GQHMobileController *mobileController = [[GQHMobileController alloc] init];
                         mobileController.qh_identifierType = @"binding";
                         mobileController.qh_mobile = USER_GET_MOBILE;
                         mobileController.qh_parameters = parameters;
                         mobileController.qh_done = YES;
                         mobileController.hidesBottomBarWhenPushed = YES;
                         [self.navigationController pushViewController:mobileController animated:YES];
                         
                     } else {
                         
                         GQHUserModel *userModel = [GQHUserModel yy_modelWithDictionary:data];
                         
                         [[NSUserDefaults standardUserDefaults] setObject:userModel.qh_userID forKey:USER_ID];
                         [[NSUserDefaults standardUserDefaults] setValue:userModel.qh_avatar forKey:USER_AVATAR];
                         [[NSUserDefaults standardUserDefaults] setObject:userModel.qh_userNickname forKey:USER_NAME];
                         [[NSUserDefaults standardUserDefaults] setObject:userModel.qh_mobile forKey:USER_MOBILE];
                         [[NSUserDefaults standardUserDefaults] setObject:userModel.qh_userTypeCode forKey:USER_TYPE];
                         [[NSUserDefaults standardUserDefaults] setObject:userModel.auditState forKey:USER_STATUS];
                         
                         NSNumber *score = [NSNumber numberWithFloat:userModel.qh_score];
                         [[NSUserDefaults standardUserDefaults] setValue:score forKey:USER_SCORE];
                         
                         [[NSUserDefaults standardUserDefaults] synchronize];
                         
                         if ([userModel.qh_userTypeCode isEqualToString:@"0"]) {
                             
                             [[NSUserDefaults standardUserDefaults] setValue:@"03" forKey:USER_STATUS];
                             
                             GQHRoleController *roleController = [[GQHRoleController alloc] init];
                             [self.navigationController pushViewController:roleController animated:YES];
                         } else {
                             
                             GQHTabBarController *tabBarController = [[GQHTabBarController alloc] init];
                             [[UIApplication sharedApplication] keyWindow].rootViewController = tabBarController;
                         }
                     }
                 } else {
                     
                     [self showToastWithText:message];
                 }
             } failure:^(NSError *error) {
                 
                 NSString *errorString = [NSString stringWithFormat:@"网络出错:%@,code:%ld", error.domain, (long)error.code];
                 [self showToastWithText:errorString];
             }];
         }
     }];
}

#pragma mark --TargetMethod
- (IBAction)displayLoginView:(UIButton *)sender {
    
    userLoginMarkView.hidden = NO;
    userRegisterMarkView.hidden = YES;
    [containerView qh_removeAllSubviews];
    
    GQHLoginView *loginView = [[GQHLoginView alloc] initWithFrame:containerView.bounds];
    loginView.qh_delegate = self;
    [containerView addSubview:loginView];
}

- (IBAction)displayRegisterView:(UIButton *)sender {
    
    userLoginMarkView.hidden = YES;
    userRegisterMarkView.hidden = NO;
    [containerView qh_removeAllSubviews];
    
    GQHRegisterView *registerView = [[GQHRegisterView alloc] initWithFrame:containerView.bounds];
    registerView.qh_delegate = self;
    [containerView addSubview:registerView];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    // 全局统一收起键盘
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}

#pragma mark --PrivateMethod

#pragma mark --Setter

#pragma mark --Getter

#pragma mark --View
- (void)loadUserInterface {
    
    UIImageView *iconImageView = [[UIImageView alloc] init];
    iconImageView.image = [UIImage imageNamed:@"login_icon"];
    [self.view addSubview:iconImageView];
    [iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerX.mas_equalTo(self.view);
        make.centerY.mas_equalTo(self.view).with.multipliedBy(0.25);
        make.width.and.height.mas_equalTo(60);
    }];
    
    UIImageView *captionImageView = [[UIImageView alloc] init];
    captionImageView.image = [UIImage imageNamed:@"login_caption"];
    [self.view addSubview:captionImageView];
    [captionImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(iconImageView.mas_bottom).with.offset(0.1 * 0.25 * GQH_SCREEN_HEIGHT);
        make.centerX.mas_equalTo(self.view);
        make.width.mas_equalTo(70);
        make.height.mas_equalTo(20);
    }];
    
    UIButton *userLoginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    userLoginButton.titleLabel.font = kBiggerFont;
    [userLoginButton setTitle:@"用户登录" forState: UIControlStateNormal];
    [userLoginButton setTitleColor:kWhiteColor forState:UIControlStateNormal];
    [userLoginButton addTarget:self action:@selector(displayLoginView:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:userLoginButton];
    [userLoginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(self.view).with.offset(0.25 * GQH_SCREEN_HEIGHT);
        make.height.mas_equalTo(40);
        make.centerX.mas_equalTo(self.view.mas_centerX).with.multipliedBy(0.5);
        make.width.mas_equalTo(100);
        
    }];
    
    userLoginMarkView = [[UIView alloc] init];
    userLoginMarkView.layer.cornerRadius = 1.0;
    userLoginMarkView.layer.masksToBounds = YES;
    userLoginMarkView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:userLoginMarkView];
    [userLoginMarkView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.and.right.mas_equalTo(userLoginButton);
        make.top.mas_equalTo(userLoginButton.mas_bottom);
        make.height.mas_equalTo(2);
    }];
    
    UIButton *userRegisterButton = [UIButton buttonWithType:UIButtonTypeCustom];
    userRegisterButton.titleLabel.font = kBiggerFont;
    [userRegisterButton setTitle:@"用户注册" forState:UIControlStateNormal];
    [userRegisterButton setTitleColor:kWhiteColor forState:UIControlStateNormal];
    [userRegisterButton addTarget:self action:@selector(displayRegisterView:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:userRegisterButton];
    [userRegisterButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.and.width.and.height.mas_equalTo(userLoginButton);
        make.centerX.mas_equalTo(self.view.mas_centerX).with.multipliedBy(1.5);
    }];
    
    userRegisterMarkView = [[UIView alloc] init];
    userRegisterMarkView.layer.cornerRadius = 1.0;
    userRegisterMarkView.layer.masksToBounds = YES;
    userRegisterMarkView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:userRegisterMarkView];
    [userRegisterMarkView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.and.right.mas_equalTo(userRegisterButton);
        make.top.mas_equalTo(userRegisterButton.mas_bottom);
        make.height.mas_equalTo(2);
    }];
    
    containerView = [[UIView alloc] init];
    containerView.backgroundColor = kClearColor;
    [self.view addSubview:containerView];
    [containerView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(userLoginMarkView.mas_bottom);
        make.left.and.bottom.and.right.mas_equalTo(self.view);
    }];
    
    // 约束立即生效
    [self.view layoutIfNeeded];
}

- (void)viewAgreeAction:(UIButton *)sender
{
    
}

@end
